#!/usr/bin/env node

const fs = require('fs')
const path = require('path')
const inquirer = require('inquirer')
const ejs = require('ejs')

let writeFileAnswer;

const writeFile = (answers) => {
    return (tmplDir, destDir) => {
        fs.readdir(tmplDir, (err, files) => {
            if(err) throw err
            files.forEach(file => {
                let fsPath = path.join(tmplDir, file)
                if(fs.statSync(fsPath).isFile()) {
                    // 渲染文件
                    ejs.renderFile(path.join(tmplDir, file), answers, (err, result) => {
                        if(err) throw err
        
                        fs.writeFileSync(path.join(destDir, file), result)
                    })
                }else {
                    // 渲染目录
                    let dir = file
                    fs.mkdirSync(dir)
                    writeFileAnswer(path.join(tmplDir, dir), path.join(destDir, dir))
                }
            })
        })
    }
}

inquirer.prompt([
    {
        type: 'input',
        name: 'name',
        message: 'Project name?'
    }
])
.then(answers => {
    const tmplDir = path.join(__dirname, 'templates');
    const destDir = process.cwd();
    writeFileAnswer = writeFile(answers)
    writeFileAnswer(tmplDir, destDir)
})